use(["public/javascripts/service/highVolumeOrdersService.js",
        "public/javascripts/widget/slider/slider.js",
        'public/javascripts/widget/prompt/prompt.js',
        "public/javascripts/widget/dialog/dialog.js",
        "public/javascripts/highVolumeOrders/view.js",
        "public/javascripts/widget/loading/loading.js"],
    function(highVolumeOrdersService,SliderComponent,PromptComponentprompt,DialogComponent,jQView,LoadingComponent) {
    var PageComponent = React.createClass({
        restData:{
            'q':'',
            'batchNumber':0,
            'pageIndex':1,
            'pageSize':10,
            'verifiedStatus':undefined
        },
        componentDidMount: function() {
            //有可能从详情过来
            var batchNumber = easyMe.getQueryString('batchNumber') ;
            var pageIndex = easyMe.getQueryString('pageIndex');
            var pageSize = easyMe.getQueryString('pageSize');

            var q='';
            var reg = new RegExp("(^|&)"+ 'q' +"=([^&]*)(&|$)"); //规避下汉字的问题
            var r = window.location.search.substr(1).match(reg);

            if(r &&r.length > 2){
                q = decodeURIComponent(r[2]);
            }



            var verifiedStatus = easyMe.getQueryString('verifiedStatus');

            this.restData.batchNumber = batchNumber? batchNumber:0;
            this.restData.pageIndex = pageIndex? pageIndex:0;
            this.restData.pageSize = pageSize? pageSize:10;
            this.restData.q = q? q:'';
            this.restData.verifiedStatus = verifiedStatus;



            if(q){
                $("#search").val(q);
            }


            if(verifiedStatus === 'false'){
                $("#showFailOrders").removeClass("unchecked").addClass("checked");
            }

            if(batchNumber){
                this.search();
            }

            jQView.init();

        },
        receiveMsg: function(data) {

        },
        getInitialState: function () {


            return {
                pageIndex: 1,
                pageSize:10,
                verifiedStatus:undefined,
                totalResult: 0,
                selectId:'',
                batchNumber:'',
                list: this.props.data.list,
                selectLength: 0,
                selectItem: [],
                summitOk:false,
                saveDraftOk:false
            };
        },
        enter: function(){
            var _this = this;

            if(event.keyCode != 13){
                return;
            }

            _this.search(true);
        },
        search:function (isReset) {

            var _this = this;

            _this.restData.q = $('#search').val();

            isReset ? _this.restData.pageIndex = 1 : '';

            var config = {
                'urlParams':{
                    'batchNumber':_this.restData.batchNumber,
                    'q':_this.restData.q,
                    'verifiedStatus':$('#showFailOrders').hasClass("checked")? false:undefined,
                    'pageIndex':_this.restData.pageIndex,
                    'pageSize':_this.restData.pageSize
                }
            };

            highVolumeOrdersService.getHighVolumeOrderList(config, function (res) {

                //loading.hidden();
                if(res.errorCode === 0){
                    _this.refresh(res);
                }else {

                    PromptComponentprompt.init({
                        msg: res.errorMsg,
                        type: 'warning'
                    }).show();
                }
            });

        },
        refresh: function(res){
            var _this = this,
                data = res.data,
                arr = [];

            for(var i=0, l=data.length; i<l; i++){
                arr.push(data[i]);
            }

            _this.setState({
                list:arr,
                'totalResult':res.pagination.totalResult, //总共的数量
                'pageIndex':res.pagination.currentPage, //页数
                'pageSize':res.pagination.pageSize, //一页展示数量
                'totalPage':res.pagination.totalPage});//总页数
        },
        onPageChange:function(pageIndex, pageSize){

            var _this = this;
            _this.restData.pageIndex = pageIndex;
            _this.restData.pageSize = pageSize;

            _this.search();
        },
        removeOrders:function () {
            var selectList = this.state.selectItem;
            if (!selectList.length) {
                PromptComponentprompt.init({'type': 'warning', "msg":"请先选择数据！"}).show();
                return;
            }
            var _this = this;
            DialogComponent.init({
                'type':'delete',
                'msg':'确定删除？',
                'success':function(){
                    var param ={
                        "urlParams":selectList,
                        "seatParams": {
                            batchNumber: _this.restData.batchNumber
                        }
                    };

                    highVolumeOrdersService.removeOrders(param, function (res) {
                        if (res.errorCode === 0) {
                            PromptComponent.init({
                                type: 'success',
                                msg: res.msg
                            }).show();
                            _this.setState({ selectItem: [], selectLength: 0 });
                            _this.search(true);
                        }else{
                            PromptComponent.init({
                                type: 'warning',
                                msg: res.msg
                            }).show();
                        }
                    })
                }
            }).show();

        },
        showTips:function () {
            if (this.state.list.length) {
                DialogComponent.init({
                    'type':'delete',
                    'msg':'新导入的数据会覆盖当前数据，确认导入？',
                    'success':function(){
                        $('#upLoadFile').click();
                    }
                }).show();
            }else{
                $('#upLoadFile').click();
            }
        },
        // gotoOrderDetail:function (item) {
        //     var _this = this;
        //     window.location.href='http://' + location.host+'/orders?'+
        //                          'highVolumeOrderId=' + item.id +
        //                          '&highVolumeBatchNumber=' + _this.state.list.batchNumber +
        //                          '&pageSize=' + 10 +'&pageIndex=' + 1 + "&related=highVolumeOrders"
        // },
        uploadFile:function (e) {
            var _this=this;
            var file = (e.srcElement || e.target).files[0];
            var fileUrl,fileData,myXhr;
            var progress = $('#progress');
            var option = {'maxSize': 10 * 1024 * 1024};



            if (file === undefined ){
                $("#upLoadFile").val('');
                return false;
            }

            if (file.size > option.maxSize) {
                $("#upLoadFile").val('');
                return PromptComponentprompt.init({
                    msg: '单个文件最大支持10M!',
                    type: 'warning'
                }).show();
            }
            if (file.size == 0) {
                $("#upLoadFile").val('');
                return PromptComponentprompt.init({
                    msg: '文件不能为空！',
                    type: 'warning'
                }).show();
            }


            var nameIdx = file.name.lastIndexOf('.');
            var nameCode = file.name.substring(nameIdx + 1, file.name.length).toUpperCase();
            if( !( nameCode==='XLSX')
            ){
                $("#upLoadFile").val('');
                return PromptComponentprompt.init({
                    msg: '文件格式不支持！',
                    type: 'warning'
                }).show();
            }

            fileUrl = '/api/v1/order/batches/upload';
            fileData = new FormData();
            fileData.append('file', file);
            var loading = LoadingComponent.init();
            loading.show();

            $.ajax({
                type:'POST',
                url:fileUrl,
                data: fileData,
                processData: false,
                contentType: false,
                error:function () {
                    loading.hidden();
                    PromptComponentprompt.init({
                        msg: "服务器异常，请重试！",
                        type: "warning"
                    }).show();
                },
                success:function(res){
                    loading.hidden();
                    if(res.errorCode === 0 ){
                        //如果有错误信息，展示错误信息
                        var errorTips;
                        if(res.data.errorNum) {
                            errorTips = '您有'+res.data.errorNum+'信息错误，请在列表中修改';

                            DialogComponent.init({
                                'type':'delete',
                                'msg':errorTips,
                                'success':function(){
                                    _this.setState({"batchNumber":res.data.batchNumber})
                                    _this.restData.batchNumber = res.data.batchNumber;
                                    _this.search(true)
                                }
                            }).show();
                        }else{
                            _this.setState({"batchNumber":res.data.batchNumber})
                            _this.restData.batchNumber = res.data.batchNumber;
                            _this.search(true)
                        }
                    }else{

                        PromptComponentprompt.init({
                            msg: res.msg,
                            type: "warning"
                        }).show();
                    }
                }
            });
            $("#upLoadFile").val('');
        },
        chooseOrderStatus:function () {
            var _this = this;

            var checkStatus = $("#showFailOrders").hasClass("unchecked") ? undefined:false;
            _this.setState({"verifiedStatus":checkStatus})
            this.restData.verifiedStatus = checkStatus;

            _this.search(true);
        },
        selectItemFn: function (item, e) {

            e.stopPropagation();
            var checked = e.target.checked,
                selectItem = this.state.selectItem,
                selectLength = this.state.selectLength,
                _this = this;
            if (item === 'all') {
                if (checked) {
                    selectItem = this.state.list.map(function(item) {
                        return item.id;
                    });

                    selectLength = this.state.list.length;
                } else {
                    selectItem = [];
                    selectLength = 0;
                }
            } else {
                if (checked) {
                    selectItem.push(item.id);
                    selectLength += 1;
                } else {
                    var index = selectItem.indexOf(item.id);
                    selectItem.splice(index, 1);
                    selectLength -= 1;
                }
            }
            this.setState({ selectItem: selectItem, selectLength: selectLength});
        },
        saveDraft:function () {
            var _this = this;
            var config = {
                'urlParams':{
                    'batchNumber':_this.state.batchNumber
                }
            };
            if(_this.state.list.length === 0) {
                return PromptComponentprompt.init({
                    msg: '请先导入数据！',
                    type: 'warning'
                }).show();

            }else{
                DialogComponent.init({
                    'type':'delete',
                    'msg':'确认保存为草稿？',
                    'success':function(){
                        var config={
                            'seatParams':{
                                'batchNumber':_this.restData.batchNumber
                            }
                        }
                        var loading = LoadingComponent.init();
                        loading.show();

                        highVolumeOrdersService.saveDraft(config,function (res) {
                            loading.hidden();

                            if(res.errorCode == 0){
                                // PromptComponent.init({
                                //     type: 'success',
                                //     msg: res.msg
                                // }).show();
                                // _this.search();

                                _this.setState({"saveDraftOk":true})

                            }else{
                                _this.setState({"saveDraftOk":false})
                                PromptComponentprompt.init({
                                    msg: res.msg,
                                    type: "warning"
                                }).show();
                            }
                        })
                    }
                }).show();
            }

        },
        summitOrders:function () {
            var _this = this;

            if(_this.state.list.length === 0){
                return PromptComponentprompt.init({
                    msg: '请先导入数据！',
                    type: 'warning'
                }).show();
            }else{
                DialogComponent.init({
                    'type':'delete',
                    'msg':'确认提交？',
                    'success':function(){
                        var config={
                            'seatParams':{
                                'batchNumber':_this.restData.batchNumber
                            }
                        }

                        var loading = LoadingComponent.init();
                        loading.show();

                        highVolumeOrdersService.commitHighVolumeOrders(config,function (res) {
                            loading.hidden();
                            if(res.errorCode == 0){
                                _this.setState({"summitOk":true})
                            }else{
                                PromptComponentprompt.init({
                                    msg: res.msg,
                                    type: "warning"
                                }).show();
                                _this.setState({"summitOk":false})
                            }
                        })


                    }
                }).show();
            }

        },
        leaveTips:function(){
            if(this.state.list.length){
                DialogComponent.init({
                    'type':'delete',
                    'msg':'未处理订单将被丢弃，确认离开？',
                    'success':function(){
                        window.location.href = "/product_list";
                    }
                }).show();
            }else{
                window.location.href = "/product_list";
            }


        },
        jumpToOrderDetail:function (item) {
            var component = this;
            //在跳转之前，把url给改了
            var historyUrl = "/highVolumeOrders?&batchNumber="+ component.restData.batchNumber +'&q='+component.restData.q +
            '&verifiedStatus='+component.restData.verifiedStatus+'&pageSize=' + component.restData.pageSize +'&pageIndex=' + component.restData.pageIndex + "&relate=product_list"

            window.history.replaceState({}, '', historyUrl);


            window.location.href = '/orders?'+ 'highVolumeOrderId=' + item.id + '&batchNumber=' + component.restData.batchNumber +'&q='+component.restData.q + 
                                   '&verifiedStatus='+component.restData.verifiedStatus+'&pageSize=' + component.restData.pageSize +'&pageIndex=' + component.restData.pageIndex + 
                                   "&related=highVolumeOrders";
            
        },
        render:function() {
            var data = this.state.data;

            var Browser = typeof window != 'undefined',
                component = this;

            return ~init;
        }
    });
    if(typeof ReactDOM != "undefined") {
        ReactDOM.render(<PageComponent data={storage}/>, document.getElementById('container'));
    }
    module.exports = PageComponent;
});